package com.itheima.reggie.controller;

import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/addressBook")
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;
    //获取收货地址
    @GetMapping("/list")
    public R<List<AddressBook>> addressList(){
        Long userId = BaseContext.getCurrendId();
        List<AddressBook> addressBooks = addressBookService.addressList(userId);
        return R.success(addressBooks);
    }
    //修改默认收货地址
    @PutMapping("/default")
    public R<String> setDefaultAddress(@RequestBody AddressBook addressBook){
        Long userId = BaseContext.getCurrendId();
        addressBook.setUserId(userId);
        addressBookService.setDefaultAddress(addressBook);
        return R.success(null);
    }
    //新增收货地址
    @PostMapping
    public R<String> addAddress(@RequestBody AddressBook addressBook){
        Long userId = BaseContext.getCurrendId();
        addressBook.setUserId(userId);
        addressBookService.addAddress(addressBook);
        return R.success(null);
    }
    //修改收货地址回显数据
    @GetMapping("/{id}")
    public R<AddressBook> addressFindOne(@PathVariable Long id){
        AddressBook addressBook = addressBookService.addressFindOne(id);
        return R.success(addressBook);
    }
    //保存修改后的收获地址
    @PutMapping
    public R<AddressBook> updateAddress(@RequestBody AddressBook addressBook){
        addressBookService.updateAddress(addressBook);
        return R.success(addressBook);
    }
    //获取最新的默认地址
    @GetMapping("/default")
    public R<AddressBook> getDefaultAddress(){
        Long userId = BaseContext.getCurrendId();
        AddressBook addressBook = addressBookService.getDefaultAddress(userId);
        if (addressBook==null){
            return R.error("请添加收货地址");
        }
        return R.success(addressBook);
    }
    //删除收货地址
    @DeleteMapping
    public R<String> removeAddress(Long ids){
        addressBookService.removeAddress(ids);
        return R.success("删除成功");
    }
}
